package com.zzyl.framework.interceptor;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class MemberInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;

    /**
     * 拦截到请求
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 如果不是Controller层的请求，直接放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //1.获取Header中的token
        String token = request.getHeader("authorization");
        if (StrUtil.isBlank(token)) {
            //说明没登录，返回401
            response.setStatus(401);
            response.setContentType("application/json;charset=UTF-8");
            AjaxResult ajaxResult = AjaxResult.error(401, "认证失败");
            response.getWriter().write(JSONUtil.toJsonStr(ajaxResult));
            return false;
        }
        //2.解析token
        try {
            Claims claims = tokenService.parseToken(token);
            Long userId = claims.get("userId",Long.class);
            if(userId==null){
                response.setStatus(401);
                response.setContentType("application/json;charset=UTF-8");
                AjaxResult ajaxResult = AjaxResult.error(401, "认证失败");
                response.getWriter().write(JSONUtil.toJsonStr(ajaxResult));
                return false;
            }
            //放到ThreadLocal
            UserThreadLocal.set(userId);
            //放行
            return true;
        } catch (Exception e) {
            //只要发现有任何的异常，都可以认为是解析失败
            log.error("解析token出现异常：",e);
            response.setStatus(401);
            response.setContentType("application/json;charset=UTF-8");
            AjaxResult ajaxResult = AjaxResult.error(401, "认证失败");
            response.getWriter().write(JSONUtil.toJsonStr(ajaxResult));
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}